package com.zywh.copyright.oauth.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {



    private Map<String, JSONObject> userMap = new HashMap<>();

    public UserDetailsServiceImpl(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userName","ljp");
        jsonObject.put("password","123456");
        jsonObject.put("role","admin");
        userMap.put("ljp",jsonObject);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("userName","xyhs");
        jsonObject1.put("password","123456");
        jsonObject1.put("role","user");
        userMap.put("xyhs",jsonObject1);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(userMap.get(username) == null){
            throw new UsernameNotFoundException("系统用户 " + username + " 不存在!");
        }
        JSONObject jsonObject = userMap.get(username);
        UserDetails user = User.withUsername(jsonObject.getString("userName"))
                //new BCryptPasswordEncoder().encode(jsonObject.getString("password"))
                .password( new BCryptPasswordEncoder().encode(jsonObject.getString("password")))
                .roles(jsonObject.getString("role")).authorities(AuthorityUtils.commaSeparatedStringToAuthorityList(jsonObject.getString("role"))).build();

        return user;
    }


}
